﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ListNetRanker
{
    public class ListNetModule
    {
        private double[] weights;
        private Normalizer normalizer;

        private ListNetModule() { }

        //Create a new model instance from encoded file
        public static ListNetModule CreateInstance(string f)
        {
            StreamReader sr = new StreamReader(f);
            BinaryReader reader = new BinaryReader(sr.BaseStream);
            int featureSize = reader.ReadInt32();

            double[] weights = new double[featureSize];
            List<Range> mms = new List<Range>();

            for (int i = 0; i < featureSize; i++)
            {
                double max = reader.ReadDouble();
                double min = reader.ReadDouble();

                mms.Add(new Range(max, min));
            }

            for (int i = 0; i < featureSize; i++)
            {
                weights[i] = reader.ReadDouble();
            }

            ListNetModule lnm = new ListNetModule();
            lnm.weights = weights;
            lnm.normalizer = new Normalizer(mms);

            return lnm;
        }


        //Create a new model instance by given weight list and normalizer
        public static ListNetModule CreateInstance(double[] w, Normalizer nor)
        {
            ListNetModule m = new ListNetModule();
            m.weights = w;
            m.normalizer = nor;

            return m;
        }

        //Write the model into file
        public void write(string strModelFileName)
        {
            StreamWriter sw = new StreamWriter(strModelFileName);
            BinaryWriter writer = new BinaryWriter(sw.BaseStream);
            List<Range> maxmins = normalizer.maxminList;

            writer.Write(maxmins.Count);
            foreach (Range maxmin in maxmins)
            {
                writer.Write(maxmin.getMax());
                writer.Write(maxmin.getMin());
            }

            for (int i = 0; i < weights.Length; i++)
            {
                writer.Write(weights[i]);
            }
            writer.Close();
        }

        public Normalizer GetNormalizer()
        {
            return normalizer;
        }

        //Get the ranking score according weight list
        public double GetRankScore(List<Double> weightList)
        {
            return DotMultiply.dotMutply(weights, weightList);
        }
    }
}
